package cn.edu.bjtu.toychange.dao;

import java.util.ArrayList;

import org.hibernate.Session;

import cn.edu.bjtu.toychange.entity.TransRecord;

public class TransRecordDao extends BaseDao {
	private Session session;
	
	public TransRecordDao() {
		session = getSession();
	}
	
	// 添加或更新交易记录
	public boolean saveTransRecord(TransRecord transRecord) {
		
		session.beginTransaction();
		try {
			session.saveOrUpdate(transRecord);
		} catch (Exception e) {
			return false;
		}
		
		session.close();
		
		return true;
	}

	// 获取交易记录
	public TransRecord getTransRecord(int transRecordID) {
		return (TransRecord) getSession().get(TransRecord.class, transRecordID);
	}
	
	public boolean commentTransaction(int transRecordID, int comment, int userID) {
		TransRecord transRecord = this.getTransRecord(transRecordID);
		
		try {
			session.beginTransaction();
			int id = (int) session.createQuery("SELECT T_userAID FROM transrecord where T_transRecordID = ?")
					.setInteger(0, transRecord.getT_transRecordID()).uniqueResult();
			session.close();
			
			if (userID == id) {
				transRecord.setT_userAComment(comment);
			} else {
				transRecord.setT_userBComment(comment);
			}
			
			this.saveTransRecord(transRecord);
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<TransRecord> getUserTransactionRecords(int userID) {
		session.beginTransaction();
		ArrayList<TransRecord> transRecordList = (ArrayList<TransRecord>) session.createQuery("SELECT * FROM transrecord where T_userAID = ? OR T_userBID = ?")
				.setInteger(0, userID).setInteger(0, userID).list();
		session.close();
		
		return transRecordList;
	}
}
